package com.alks.yn_zs.service.serviceImpl;

import com.alibaba.excel.util.StringUtils;
import com.alks.common.aop.AutoPageAop;
import com.alks.entity.data.page.PageParam;
import com.alks.entity.data.page.PageRecord;
import com.alks.yn_zs.data.dto.FinishStoreDTO;
import com.alks.yn_zs.data.dto.StatsDto;
import com.alks.yn_zs.data.request.StatsRequest;
import com.alks.yn_zs.format.DateFormat;
import com.alks.yn_zs.mapper.SoleShowMapper;
import com.alks.yn_zs.service.ISoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author MS
 * @since 2025/10/2216:07
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SoleServiceImpl implements ISoleService {
    private final SoleShowMapper soleMapper;

    @Override
    public List<StatsDto> blankState(StatsRequest request) {
        /*初始化*/
        String unit = StringUtils.isBlank(request.getTitleUnit()) ? DateFormat.DEF_UNIT : request.getTitleUnit();
        Integer pushUnit = request.getPushUnit() == null ? DateFormat.DEF_PUSH : request.getPushUnit();
        LocalDate endDate = request.getEndDate() == null ? DateFormat.DEF_END_DATE : request.getEndDate();
        LocalDate startDate = DateFormat.dateStartFormat(unit, pushUnit, endDate);
        String typeCode = "1";
        String[] type = {"入库", "出库"};
        /*获取发料数据*/
        List<StatsDto> prodList = soleMapper.soleStateQuery(startDate, endDate, typeCode);
        List<StatsDto> dtoList = new ArrayList<>();
        if (prodList==null){
            return dtoList;
        }
        Map<String, List<StatsDto>> prodGroupMap = prodList.stream()
                .collect(Collectors.groupingBy(a -> a.getType()+"_"+DateFormat.formatKey(unit, a.getDate())));
        prodGroupMap.forEach((key, value)->{
            StatsDto dto = new StatsDto();
            BigDecimal count = value.stream()
                    .map(StatsDto::getCount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            dto.setDate(value.get(0).getDate());
            String[] split = key.split("_");
            dto.setType(split[0]);
            dto.setTitle(split[1]);
            dto.setCount(count);
            dtoList.add(dto);
        });
        DateFormat.fillMissingAndSort(dtoList,unit,startDate,endDate,type);
        dtoList.sort(Comparator
                .comparing(StatsDto::getType)
                .thenComparing(StatsDto::getDate, Comparator.nullsFirst(Comparator.naturalOrder()))
        );
        return dtoList;

    }

    @Override
    @AutoPageAop
    public PageRecord<FinishStoreDTO> blankList(PageParam request) {
        return new PageRecord<>(soleMapper.blankList());
    }
}
